package com.lsk.mobile;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.alipay.constants.AlipayServiceEnvConstants;
import com.lsk.util.ReturnData;
import com.lsk.util.Syslog;
import com.lsk.util.UtilUUID;

import java.util.Map;
import java.util.UUID;

public class ApplyService {

    Cache cache= Redis.use();

    /**
     * 获取支付宝token
     */
    public ReturnData getUserId(String code){

        ReturnData returnData=new ReturnData();

        String userId="";

        try {

            String publicKey = "sys_config";

            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    cache.get(publicKey + "applyAppId").toString() + "", cache.get(publicKey + "applyPrivateKey").toString() + "",
                    "json", "GBK", cache.get(publicKey + "applyPublicKey").toString(), "RSA2");
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(code);
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);

            userId=response.getUserId();

            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }

        } catch (Exception e) {

            Syslog.error(e);

        }

        returnData.setResult(true);

        return returnData;
    }


    /**
     * 验签
     *
     * @param ‘
     * @return
     */
    public void verifySign(Map<String, String> params) throws AlipayApiException {

        if (!AlipaySignature.rsaCheckV2(params, AlipayServiceEnvConstants.ALIPAY_PUBLIC_KEY,
                AlipayServiceEnvConstants.SIGN_CHARSET, AlipayServiceEnvConstants.SIGN_TYPE)) {
            throw new AlipayApiException("verify sign fail.");
        }
    }


    public  String encryptAndSign(String bizContent, String alipayPublicKey, String cusPrivateKey, String charset,
                                        boolean isEncrypt, boolean isSign, String signType) throws AlipayApiException {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isEmpty(charset)) {
            charset = AlipayConstants.CHARSET_GBK;
        }
        sb.append("<?xml version=\"1.0\" encoding=\"" + charset + "\"?>");
        if (isEncrypt) {// 加密
            sb.append("<alipay>");
            String encrypted = AlipaySignature.rsaEncrypt(bizContent, alipayPublicKey, charset);
            sb.append("<response>" + encrypted + "</response>");
            sb.append("<encryption_type>AES</encryption_type>");
            if (isSign) {
                String sign = AlipaySignature.rsaSign(encrypted, cusPrivateKey, charset, signType);
                sb.append("<sign>" + sign + "</sign>");
                sb.append("<sign_type>");
                sb.append(signType);
                sb.append("</sign_type>");
            }
            sb.append("</alipay>");
        } else if (isSign) {// 不加密，但需要签名
            sb.append("<alipay>");
            sb.append("<response>" + bizContent + "</response>");
            String sign = AlipaySignature.rsaSign(bizContent, cusPrivateKey, charset, signType);
            sb.append("<sign>" + sign + "</sign>");
            sb.append("<sign_type>");
            sb.append(signType);
            sb.append("</sign_type>");
            sb.append("</alipay>");
        } else {// 不加密，不加签
            sb.append(bizContent);
        }
        return sb.toString();
    }
    /**
     * 支付宝小程序获取userId
     */
    public ReturnData getApplyUserId(String coede,String name){

        ReturnData returnData=new ReturnData();
        try {

            String appId="2019051464473437";

            String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCVKGjIIstc4NA4+9QL2FdFQWA8+Oq/Kl8fCQ5S3deoXnL0V+kyU3VUbQsZAsXebUM//yF7nHdzTLaiJi0UKakI/6CK+T6rG0CGbfXx3Rxmh8DkvDbnayyFUwvMN5PlCB9qanamoeDizduRZnQ+hL388SXpr35g6ck3WsUJtQozt0ul6yPlNghVfc8Ihk0hVXQCBbZAfllUMXxQswDxFPzhnONZ6VpJsJWfyruRSANGoTmixycfQvqZ+RAEB0xcN0Y9H2ZLIG8qPlocgXHMypKkwcA/IlyKR7rPxwQcMWMGBML1bpNJTrgSvabTjs9U263GhUSQAl71xEyPN7hCMi1nAg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pqU0/v7qlJozZm4Toa9PE/KENooEPOj72PJRdC+UXZl4oXj9tyb4Nhe+iDBivd4N+xq/mjYV/VihWwjOZGnaUuyz3gvXUp9pvgycxtbf6WQ0GYL5UDhlfoD7qfNlYRvMtYQsihe0RqFiQS4";

            String alipayPublic="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiF+Qpsm30dQlDSAPxiFrGNBOqV7jwf94YnuUNNdnZWAzrF0HI7gby0s604ojsMZHY+kXLeh0eG6La87sGm7YV3YKhcSTReQKFUaJIqn//lRSbvBWpMLKaCmHIgzLZ5EM3c2o/NXZZbYdCIzOvjigWsoiS/SSXaoDpP62yzfOmSBfwx5bJT+yNo40tJhAj1m0ztPqv7GwDIS4Z1ybpv7O2eDjQktV0+fxCWveQ4QN0L0cbqTOrEaJfEfRQCEvb/sLbgENE80Q8Kx/i1GI+5OXIz/Ci0Wx/nNmN+us1kde3zuUa5lueJR83mjdjRcA7CxmSn5MxmKY/U42HAzXicBh+QIDAQAB";
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    appId,privateKey,"json","GBK",
                    alipayPublic,"RSA2");
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(coede);
            request.setRefreshToken(UtilUUID.getOrderIdByUUId());

            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);

            Syslog.info("请求支付宝的参数为："+response.getParams());

            if(response.isSuccess()){
                System.out.println("调用成功");
                String userId=response.getUserId();
                AppletService appletService=new AppletService();



                returnData=appletService.apiupMemberService(userId,name,"");
            } else {

                System.out.println("调用失败");

                returnData.setResult(false);
            }

        }catch (Exception e){

            Syslog.error(e);
        }

        return returnData;

    }

}
